<?php

/**
 * @version		$Id: hello.php 15 2009-11-02 18:37:15Z chdemko $
 * @package		Joomla16.Tutorials
 * @subpackage	Components
 * @copyright	Copyright (C) 2005 - 2010 Open Source Matters, Inc. All rights reserved.
 * @author		Christophe Demko
 * @link		http://joomlacode.org/gf/project/helloworld_1_6/
 * @license		License GNU General Public License version 2 or later
 */

// No direct access to this file
defined('_JEXEC') or die('Restricted access');

// import Joomla modelitem library
jimport('joomla.application.component.modelitem');

class bgModelbg extends JModel{
	function getAllFunc(){
	   $qr = "SELECT * FROM func ORDER BY FUNC_SORT";
       $this->_db->setQuery($qr);
       $result = $this->_db->loadObjectList();
       return $result;
	}
    
    public function getAllGroupUser(){
    	$qr = "SELECT id, title FROM #__usergroups WHERE parent_id = 7 OR id=8";
        $this->_db->setQuery($qr);
		$rows = &$this->_db->loadObjectList();
        
        return $rows;
    }
    
    /**
     * bgModelbg::save()
     * Save permission to database
     * @param mixed $data
     * format $data
     * [mail_group] => Array // function
        (
            [8] => Array // group user
                (
                    [PRRM_INSERT] => 1
                    [PRRM_UPDATE] => 1
                    [PRRM_DELETE] => 0
                    [PRRM_EDITOWN] => 0
                )
                ....
     * @return
     */
    function save($data){
        $user = &JFactory::getUser();
        $id = &$user->id;
        
        // delete all table
        $qr = 'DELETE FROM perm';
        $this->_db->setQuery($qr);
        $this->_db->query();
        
        // insert
        $inserts = array();
        foreach($data as $fnc=>$groups){
            foreach($groups as $k=>$group){
       
             $inserts[] = "('$k',
                            '$fnc',
                            '$group[PRRM_INSERT]',
                            '$group[PRRM_UPDATE]',
                            '$group[PRRM_DELETE]',
                            '$group[PRRM_EDITOWN]',
                            '$id',
                            NULL) ";
            }
            
        }
        // implode array to string what is insert database
        $inserts = implode(',', $inserts);

        $qr = "INSERT INTO perm VALUES $inserts";
        $this->_db->setQuery($qr);
        
        return $this->_db->query();
    }
    
    public function getAllPermission(){
    	$qr = "SELECT * FROM perm";
        $this->_db->setQuery($qr);
        return $this->_db->loadObjectList();
    }
}
